package main

import (
	"database/sql"
	"flag"
	"html/template"
	"log"
	"net/http"
	"os"

	_ "github.com/go-sql-driver/mysql"

	"snippetbox.alan/internal/models"
)

type application struct {
	errorLog *log.Logger
	infoLog  *log.Logger
    snippets *models.SnippetModel
	templateCache map[string]*template.Template
}

func main() {

	addr := flag.String("addr", ":8080", "HTTP-network address")
    dsn := flag.String("dsn","web:pass@/snippetbox?parseTime=true","Mysql source name")
    flag.Parse()

	infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
	errLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)

    db,err := openDB(*dsn)
    if err != nil {
        errLog.Fatal(err)
    }
    defer db.Close()

	templateCache,err := newTemplateCache()
	if err != nil {
		errLog.Fatal(err)
	}

	app := &application{
		infoLog:  infoLog,
		errorLog: errLog,
        snippets: &models.SnippetModel{DB: db},
		templateCache: templateCache,
	}

	mux := app.routes()

	srv := &http.Server{
		Addr:     *addr,
		ErrorLog: errLog,
		Handler:  mux,
	}

	infoLog.Printf("Starting server on %s", *addr)
	err = srv.ListenAndServe()
	errLog.Fatal(err)
}

func openDB(dsn string) (*sql.DB, error) {
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        return nil, err
    }
    if err = db.Ping(); err != nil {
        return nil, err
    }
    return db, nil
}